<?php
session_start();
	if((!isset($_SESSION['hallpass']))||($_SESSION['hallpass']==false))
	{
		$_SESSION['error'] = "not_auth";
		header('Location: error_page.php');
	}
//$_SESSION['hallpass'] = true;
require "DBConnection.php";
//require_once "./Objects/User.php";
require_once "security.php";
//require "referer.php";


/** checks that spoofing isn't occuring, update $_SESSION['login_status'] accordingly*/
is_spoofing("login");

/*
echo "Session secret:";
echo "<br>";
echo $_SESSION['secret'];
echo "<br>";
echo "post secret";
echo "<br>";
echo $_POST['secret'];
echo "<br>";
*/
if((isset($_SESSION['spoof_status']))&&($_SESSION['spoof_status'] != -1))
{
	
	$connection = new Connection();
	$username = mysql_real_escape_string($_POST['username']);
	$password = mysql_real_escape_string($_POST['password']);
	
	$query = "SELECT w_email, pass, salt
	        FROM workertrack.worker
	        WHERE w_email = '$username'
	        UNION
	        SELECT emp_email, pass, salt
	        FROM workertrack.employer 
	        WHERE emp_email = '$username';"; 
	
	$result = $connection->execute_query($query);	//result gets the info from the DB
	$userData = mysql_fetch_array($result, MYSQL_ASSOC);
	$hash = crypt($password, $userData['salt']);
	
/*	echo "hash password is :";
	echo "<br>";
	echo $hash;
	echo "<br>";
	echo "user data password is:";
	echo "<br>";
	echo $userData['pass'];
	echo "<br>";
*/	
	
	echo mysql_num_rows($result);
	echo "<br>";
	if(mysql_num_rows($result)<1) //user does not exist
	{
/*		
		echo "<br>";
		echo "no such user ";
		echo $username;
		echo "and password: ";
		echo $password;
		echo "<br>";*/
		$_SESSION['loginflag']=0;
		session_destroy();
		header('Location: ../index.php');
		//header('Location: ../HTML/loginfailed.html');
	}
	
	else if($hash != $userData['pass'])	//password is incorrect
	{
		/*echo "<br>";
		echo "password is incorrect";*/
		$_SESSION['loginflag']=0;
		session_destroy();
		header('Location: ../index.php');
		//header('Location: ../HTML/loginfailed.html');
	}
	else if($hash == $userData['pass'])//login successful
	{
/*		echo "login success";
		echo "<br>";
		echo $hash;
		echo "<br>";
		echo $userData['pass'];*/
		//user can log in
		$_SESSION['loginflag']=1;
		$name=explode("@", $username);
		$_SESSION['userid']=$name[0];

		
		header('Location: ../index.php');
	}
	$connection->close_connection();
}	

	
	$_SESSION['hallpass'] = false;
?>